import React, { Fragment } from 'react'
import { View, StyleSheet, Text, ScrollView, Image } from 'react-native'
import { StackActions } from 'react-navigation'
import Picker from 'react-native-picker'
import moment from 'moment'
import { ScaleS, ScaleT } from 'src/utils/ScreenUtil'
import BasePage from 'src/pageP/base/base-page/index'
import CustomBoxShadow from 'src/components/boxshadow/CustomBoxShadow'
import CustomButton from 'src/components/button/CustomButton'
import CustomInputLabel from 'src/components/button/CustomInputLabel'
import JobIntentionCardContent from 'src/components/card-job-intention/content'
import NextButton from 'src/components/button/NextButton'
import PromptModal from 'src/components/modal/PromptModal'
import showPicker from 'src/utils/PickerUtil'
import {
  addJobHunting,
  // insertUserArchiveInfo,
  updateSelfEvaluation,
  getArchiveInfo,
  editJobHunting
} from 'src/utils/RequestAPI'
import { CommonToast, ShowLoading, DismissLoading } from 'src/utils/ToastUtil'
import { isEmptyObjectFn } from 'src/utils/JSTypeUtil'
import { connect } from 'react-redux'
import {
  UPDATE_USERINFO_ACTION,
  DO_REQUEST_SAVEUSERINFO_C_ACTION
} from 'src/store/actions/userinfo'
import {
  INIT_FIRST_USERINFO_C_ACTION,
  UPDATE_FIRST_USERINFO_C_ACTION
} from './store/action'
import { DO_REQUEST_MAIN_PAGE_C_ACTION } from 'src/pageC/mine/mine-page/store/action'
import { getGenderChinese } from 'src/utils/ConfigUtil'
import { showModal } from 'src/utils/ModalUtil'
import GenderChoice from 'src/components/modal/GenderChoice'
import { keywordBlock } from 'src/utils/RegUtil'

const year = new Date().getFullYear()
const years = new Array(100).fill(0).map((e, i) => `${year - i}年`)

// 发送行为
const mapDispatchToProps = dispatch => ({
  updateUserInfo (payload) {
    dispatch(UPDATE_USERINFO_ACTION(payload))
  },
  initState (payload) {
    dispatch(INIT_FIRST_USERINFO_C_ACTION(payload))
  },
  updateState (payload) {
    dispatch(UPDATE_FIRST_USERINFO_C_ACTION(payload))
  },
  doRequestSaveUserInfoToC (payload) {
    const promise = DO_REQUEST_SAVEUSERINFO_C_ACTION(payload)
    dispatch(promise)
    return promise.payload
  },
  doRequestMainPage (...payload) {
    const promise = DO_REQUEST_MAIN_PAGE_C_ACTION(...payload)
    dispatch(promise)
    return promise.payload
  }
})

@connect(
  ({ userinfo, CFirstUserInfoStore, CMineCenterStore }) => {
    const {
      workNature,
      jobPlace,
      workPlace,
      workCategory
    } = CFirstUserInfoStore
    return {
      userinfo,
      CMineCenterStore,
      ...CFirstUserInfoStore,
      jobIntention: {
        jobPlace,
        workNature,
        workPlace,
        workCategory
      }
    }
  },
  mapDispatchToProps
)
class CFirstUserInfo extends BasePage {
  constructor (props) {
    super(props)
    this.state = {
      header: {},
      saveVisible: false
    }
    const {
      initState,
      updateState,
      userinfo: { B: userinfoB, C: userinfoC },
      CMineCenterStore: { intro, jobHuntingModels = [] }
    } = this.props

    initState()
    if (!isEmptyObjectFn(userinfoB)) {
      const { userName, gmtBorth, gender } = userinfoB
      updateState({
        userName,
        gmtBorth: gmtBorth ? moment(gmtBorth).format('YYYY') : '',
        gender
      })
    }
    if (!isEmptyObjectFn(userinfoC)) {
      // 老的用户信息
      const { userName, gmtBorth, gender } = userinfoC
      updateState({
        userName,
        gmtBorth: gmtBorth ? moment(gmtBorth).format('YYYY') : '',
        gender
      })
    }
    if (intro) {
      // 老的自我评价
      updateState({
        intro
      })
    }
    if (jobHuntingModels && jobHuntingModels[0]) {
      // 老的求职意愿  提交时需要走修改接口
      const { id, jobPlace, comprehensive } = jobHuntingModels[0]
      let workPlace
      let workNature = []
      let workCategory
      try {
        const data = JSON.parse(comprehensive)
        workPlace = data.workPlace
        workNature = data.workNature
        workCategory = data.workCategory
        updateState({
          jobPlace,
          workPlace,
          workNature,
          workCategory
        })
        this.jobIntentionId = id
      } catch (error) {
        console.log('JSON.parse(comprehensive)')
      }
    }
  }

  childRender () {
    const { userName, gmtBorth, intro, gender, jobIntention } = this.props
    const { jobIntentionEnable, nextEnable } = this.state
    const { saveVisible } = this.state
    return (
      <Fragment>
        <ScrollView
          style={styles.container}
          contentContainerStyle={styles.contentContainer}
        >
          <Text style={styles.messageTitleTopDesc}>基本信息</Text>
          <Text style={styles.messageTitleBottom}>
            *完善求职信息能更快的找到心仪的工作
          </Text>
          <CustomBoxShadow
            style={{
              ...styles.infoViewShadow,
              height: ScaleS(307),
              marginTop: ScaleS(34)
            }}
          >
            <CustomInputLabel
              title="姓名"
              value={userName}
              placeHolder="请输入"
              onPress={this._nameFieldClick}
            />
            <CustomInputLabel
              title="性别"
              value={getGenderChinese(gender)}
              placeHolder="请选择"
              onPress={this._genderFieldClick}
            />
            <CustomInputLabel
              title="出生年份"
              value={gmtBorth}
              placeHolder="请选择"
              params={0}
              onPress={this._birthFieldClick}
            />
            <CustomInputLabel
              title="自我评价"
              value={intro && intro.length ? `${intro.length}字` : intro}
              placeHolder="请输入"
              params={0}
              last={true}
              onPress={this._selfEvalutionClick}
            />
          </CustomBoxShadow>
          <CustomBoxShadow
            style={{
              ...styles.infoViewShadow,
              marginTop: ScaleS(30),
              shadowRadius: ScaleS(30),
              marginBottom: ScaleS(90)
            }}
          >
            <CustomInputLabel
              title="求职意向"
              placeHolder={!jobIntentionEnable ? '请选择' : ''}
              last={!jobIntentionEnable}
              onPress={this._jobIntentionClick}
            />
            {!!jobIntentionEnable && (
              <View style={{ marginHorizontal: ScaleS(-20) }}>
                <JobIntentionCardContent dataSource={jobIntention} />
              </View>
            )}
          </CustomBoxShadow>
        </ScrollView>
        <NextButton
          style={styles.nextButton}
          title="下一步"
          enable={!!nextEnable}
          onPress={this._nextBtnClick}
        />
        <PromptModal
          visible={saveVisible}
          onCancel={this.onSaveCancel}
          onConfirm={this.onSaveConfirm}
          onModalHide={this.onSaveModalHide}
          config={{
            titleText: '温馨提示',
            contentText: '内容尚未保存，确定放弃吗？'
          }}
        />
      </Fragment>
    )
  }

  componentDidMount () {}

  static getDerivedStateFromProps (props, state) {
    // console.log('getDerivedStateFromProps', state)
    return CFirstUserInfo.saveButtonEnable(props, state)
  }

  static saveButtonEnable (props, state, tip = false) {
    const {
      userName,
      gmtBorth,
      gender,
      intro,
      workNature,
      jobPlace,
      workPlace,
      workCategory
    } = props
    const jobIntentionEnable =
      workNature &&
      workNature.length &&
      jobPlace &&
      workPlace &&
      workPlace.length &&
      workCategory &&
      workCategory.length
    const nextEnable = [
      {
        key: userName,
        value: '姓名'
      },
      {
        key: gender,
        value: '性别'
      },
      {
        key: gmtBorth,
        value: '出生年月'
      },
      {
        key: intro,
        value: '自我评价'
      },
      {
        key: jobIntentionEnable,
        value: '求职意愿'
      }
    ].every(e => {
      if (tip && !e.key) {
        CommonToast(`请完善${e.value}`)
      }
      return e.key
    })
    if (
      nextEnable !== state.nextEnable ||
      jobIntentionEnable !== state.jobIntentionEnable
    ) {
      console.log('saveEnable change----->', nextEnable, jobIntentionEnable)
      return {
        jobIntentionEnable,
        nextEnable
      }
    }
    return null
  }

  _maskClick = () => {
    console.info('maskClick')
    Picker.hideAnimated()
    this.togglePickerMask(false)
  }

  togglePickerMask = pickerMask => {
    this.setState({
      pickerMask
    })
  }

  _birthFieldClick = () => {
    const { gmtBorth } = this.props
    const pickerData = years
    const selectedValue = [`${gmtBorth || year - 18}年`]
    const pickerTitleText = '选择出生年份'
    showPicker({
      pickerData,
      selectedValue,
      pickerTitleText,
      onConfirm: ([gmtBorth]) => {
        this.props.updateState({
          gmtBorth: gmtBorth.replace(/年/, '')
        })
      }
    })
  }

  _nameFieldClick = () => {
    const saveCallback = userName => {
      this.props.updateState({
        userName
      })
    }
    const { userName: value } = this.props
    this.props.navigation.navigate('CommonInputPage', {
      title: '姓名',
      blockReg: keywordBlock.value,
      value,
      desc: '*请填写真实姓名',
      placeholder: '请输入姓名',
      maxLength: 6,
      saveCallback
    })
  }

  /**
   * 性别选择
   * @param type 0 boy ;1 girl
   */
  _genderFieldClick = () => {
    const { gender } = this.props
    const config = {
      gender,
      onConfirm: this.genderConfirm
    }
    this.genderModal = showModal(<GenderChoice {...config}/>)
  }

  genderConfirm = (gender) => {
    this.genderModal && this.genderModal.close()
    this.props.updateState({
      gender
    })
  }

  _selfEvalutionClick = () => {
    const saveCallback = intro => {
      this.props.updateState({
        intro
      })
    }
    const { intro } = this.props
    this.props.navigation.navigate('CUserSelfEvalution', {
      title: '自我评价',
      intro,
      desc: '*充分展现自我优势，让更多企业发现你',
      placeholder: '请输入自我评价',
      maxLength: 140,
      multiline: true,
      inputTextStyle: {
        minHeight: ScaleS(150)
      },
      saveCallback
    })
  }

  /**
   * 求职意向
   * @private
   */
  _jobIntentionClick = () => {
    this.props.navigation.navigate('CFirstJobNature')
  }

  /**
   * 下一步
   */
  _nextBtnClick = () => {
    const { nextEnable } = this.state
    if (!nextEnable) {
      CFirstUserInfo.saveButtonEnable(this.props, this.state, true)
      return
    }

    const {
      jobIntention: comprehensive,
      jobPlace,
      userName,
      gmtBorth,
      gender,
      intro,
      userinfo: {
        userId,
        mobile,
        C: { id }
      },
      doRequestSaveUserInfoToC,
      doRequestMainPage
    } = this.props
    ShowLoading()
    const params = {
      userName,
      gmtBorth: `${gmtBorth}-01-01 00:00:00`,
      gender,
      userId,
      id,
      mobile
    }
    doRequestSaveUserInfoToC({ params })
      .then(res => {
        return getArchiveInfo({ params: { userId } })
      })
      .then(res => {
        const archiveId = res.data.archiveId
        let jobHuntingReq = null
        if (this.jobIntentionId) {
          // 修改求职意愿
          jobHuntingReq = editJobHunting({
            params: {
              comprehensive: JSON.stringify(comprehensive),
              jobPlace,
              userId,
              userName,
              id: this.jobIntentionId
            }
          })
        } else {
          // 增加求职意愿
          jobHuntingReq = addJobHunting({
            params: {
              comprehensive: JSON.stringify(comprehensive),
              jobPlace,
              userId,
              userName,
              archiveId
            }
          })
        }
        return Promise.all([
          updateSelfEvaluation({ params: { userId, archiveId, intro } }),
          jobHuntingReq
        ])
      })
      .then(res => {
        return doRequestMainPage({ params: { userId } })
      })
      .then(res => {
        const {
          navigation: {
            state: {
              params: { fromJobdetail } = {}
            }
          }
        } = this.props

        if (fromJobdetail) {
          // 从岗位详情进入本页面
          const {
            CMineCenterStore: {
              educations = [],
              userArchiveWorkModels = []
            }
          } = this.props
          if (educations.length === 0 && userArchiveWorkModels.length === 0) {
            // 跳转到教育信息
            this.props.navigation.replace('CEducationInfoManager')
          } else {
            // 直接返回
            this.props.navigation.goBack()
          }
        } else {
          this.props.navigation.replace('CUserAvator', { firstLogin: true })
        }
      })
      .finally(() => {
        DismissLoading()
      })
  }

  goBack = () => {
    const {
      jobIntentionEnable,
      jobPlace,
      userName,
      gmtBorth,
      gender,
      intro
    } = this.props
    if (
      jobIntentionEnable ||
      jobPlace ||
      userName ||
      gmtBorth ||
      gender ||
      intro
    ) {
      this.toggleMask(true)
      return
    }
    this.props.navigation.goBack()
  }

  toggleMask = saveVisible => {
    this.setState({
      saveVisible
    })
  }

  onSaveConfirm = () => {
    this.onSaveCancel()
  }

  onSaveCancel = () => {
    this.toggleMask(false)
  }

  onSaveModalHide = ensure => {
    ensure && this.props.navigation.goBack()
  }
}

export default CFirstUserInfo

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFFFFF',
    marginBottom: ScaleS(70)
  },
  maskView: {
    width: '100%',
    height: '100%',
    position: 'absolute',
    backgroundColor: '#00000055',
    zIndex: 101
  },
  messageTitleTopDesc: {
    marginTop: ScaleS(10),
    fontSize: ScaleT(27),
    lineHeight: ScaleS(47),
    fontWeight: 'bold',
    color: '#444444',
    marginHorizontal: ScaleS(20)
  },
  messageTitleBottom: {
    fontSize: ScaleT(12),
    lineHeight: ScaleS(28),
    color: '#999999',
    marginHorizontal: ScaleS(20)
  },

  infoViewShadow: {
    width: ScaleS(335),
    shadowColor: '#9C9C9C',
    shadowRadius: ScaleS(40),
    shadowOpacity: 0.25,
    shadowOffset: {
      width: 0,
      height: ScaleS(7)
    },
    backgroundColor: 'white',
    borderRadius: ScaleS(10),
    paddingHorizontal: ScaleS(16),
    marginHorizontal: ScaleS(20)
  },
  genderView: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  genderItemView: {},
  genderItemSelected: {
    backgroundColor: '#000000'
  },
  genderItemDefault: {
    backgroundColor: '#F0F0F0'
  },
  genderItem: {
    width: ScaleS(27),
    height: ScaleS(31)
  },
  genderVerticalLine: {
    marginHorizontal: ScaleS(20),
    width: ScaleS(1),
    height: ScaleS(16),
    backgroundColor: '#D2D2D2'
  },
  nextButton: {
    position: 'absolute',
    bottom: ScaleS(20),
    left: ScaleS(32)
  }
})
